#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@File ：OrderController.py
@Author ：zqy
@Email : zqingy@work@163.com 
@note: 
"""
from flask import g
from flask_restx import Namespace, Resource

from application.Parser.OrderParser import OrderValidator
from application.controller import register_crud_model
from application.enumeration.StatusCodeEnum import StatusCodeEnum
from application.exception.BasicException import BasicException
from application.logic.OrderLogic import OrderLogic
from application.model.OrderModel import OrderStatus
from application.model.UserModel import UserPoints
from application.util.MysqlUtil import mysql_session
from application.util.ResponseUtil import ResponseUtil

order_ns = Namespace('order', description='订单模块')

order_parser: OrderValidator = OrderValidator

register_crud_model(
    ns=order_ns,
    logic_cls=OrderLogic,
    parser=order_parser,
    roles=None,
    route="",
    id_type="int",
    include_operations=["get", "list", "put", "delete", "post"]
)


@order_ns.route('/<int:_id>/cancel')
class CancelOrder(Resource):
    def delete(self, _id):
        """取消订单"""
        return ResponseUtil(data=OrderLogic.cancel(_id)).success()

@order_ns.route('/<int:_id>/delivered')
class CancelOrder(Resource):
    def post(self, _id):
        """订单标记送达"""
        o: OrderLogic.model = OrderLogic.mapper.get_info_by_id(_id)
        if not o:
            raise BasicException(status_code=StatusCodeEnum.ERROR.value, error_message="订单不存在")
        if o.user_id!= g.user.id:
            raise BasicException(status_code=StatusCodeEnum.ERROR.value, error_message="订单不是你的")
        o.status = OrderStatus.COMPLETED
        mysql_session.add(o)
        try:
            mysql_session.commit()
        except Exception as e:
            mysql_session.rollback()
            raise BasicException(status_code=StatusCodeEnum.ERROR.value, error_message="订单标记送达失败，请稍后再试")
        return ResponseUtil().success()


@order_ns.route('/<int:_id>/pay')
class PayOrder(Resource):

    def post(self, _id):
        o: OrderLogic.model = OrderLogic.mapper.get_info_by_id(_id)
        if not o:
            raise BasicException(status_code=StatusCodeEnum.ERROR.value, error_message="订单不存在")
        if o.user_id != g.user.id:
            raise BasicException(status_code=StatusCodeEnum.ERROR.value, error_message="订单不是你的")
        if o.status.value != "待支付":
            raise BasicException(status_code=StatusCodeEnum.ERROR.value, error_message="订单已支付，请勿重复支付")

        up = UserPoints.query.filter_by(user_id=g.user.id).first()
        if not up:
            up = UserPoints(user_id=g.user.id, points=int(o.total_price))
        else:
            up.points += int(o.total_price)

        mysql_session.add(up)
        o.status = OrderStatus.SHIPPED
        mysql_session.add(o)
        try:
            mysql_session.commit()
        except Exception as e:
            mysql_session.rollback()
            raise BasicException(status_code=StatusCodeEnum.ERROR.value, error_message="支付失败，请稍后再试")

        return ResponseUtil().success()
